require "cpg/plist"
require 'cpg/app'


include Cpg

def include_summer_board?(apps)
  apps.each do |app|
    if app.name =~ /[Ss]ummer[Bb]oard/
      return true
    end
  end
  return false
end

def get_app_names(apps)
  names = []
  apps.each do |app|
    names << app.name
  end
  names
end


def generate_custom_payload(xml_source)
  plist = Plist.new(xml_source)
  apps = plist.parse
  success_apps = []
  failure_apps = []
  apps.each do |app|
    if app.fetch
      success_apps << app
    else
      failure_apps << app
    end
  end
  
  # Sync installer/installer/PackageSources.plist
  success_apps.delete_if do |app|
    result = false
    app.scripts.install.each do |command|
      if command =~ /^\[AddSource\](.+)/
        add_source_url = $1
        unless plist.update_packagesources_list("payload/installer/installer/PackageSources.plist", add_source_url)
          failure_apps << app
          result = true
        end
      end
    end
    result
  end

  # clean /payload/custom_packages
  unless Dir.glob(PAYLOAD_CUSTOM_PATH).empty?
    FileUtils.rm_r(PAYLOAD_CUSTOM_PATH)
  end
  
  # create /payload/custom_packages
  Dir.mkdir(PAYLOAD_CUSTOM_PATH)


  # unzipping source/* into payload/custom_packages/APP_NAME
  
  app_source_files = Dir.glob("source/*")
  app_source_files.each do |file|
    success_app_names = get_app_names(success_apps)
    file =~ /.+\/(.+)\.zip$/
    name = $1
    if success_app_names.include?(name)
      Dir.mkdir("#{PAYLOAD_CUSTOM_PATH}/#{name}")
      pipe = open("|unzip -q -o -K #{file} -d #{PAYLOAD_CUSTOM_PATH}/#{name}")
      pipe.close
    end
  end


  print "starting to write into do_payload.sh .."
  
  
  File.open("payload/do_payload.sh", "r+") do |file|
    # this must be first
    old_content = file.readlines
    
    file.puts "\n\n"
    file.puts "# Custom App package:  \n"
    file.puts "\n\n"
    file.puts "# Fix Installer owner  \n" #我不確定除了這個還有哪些權限會有問題 有的話我會加在這邊
    file.puts "chown -R root:wheel /var/mobile/Library/Installer \n"
    file.puts "chown    root:wheel /var/mobile/Library/Preferences/com.apptapp.Installer.plist \n"
    file.puts "\n\n"
    
    if include_summer_board?(apps)
      file.puts "# Fiex SummerBoard Install Script....."
      file.puts "mkdir -p /var/mobile/Library/SummerBoard/Themes /Library/MobileEnhancer/libexec \n"
      #無奈的配合
      file.puts "mkdir -p /var/Library"
      file.puts "cp -pfr /Library/Wallpaper /var/Library \n"
      file.puts "rm -rf /Library/Wallpaper \n"
      file.puts "ln -s /var/Library/Wallpaper /Library/Wallpaper"
      file.puts "\n\n"
    end
    
    success_apps.each do |app|
      file.puts "# #{app.name} "
      app.scripts.install.each do |cmd|
        file.puts cmd
      end
      file.puts ""
    end
  end
  
  puts "[OK]"

  print "Starting to update LocalPackages.plist.."
  # update LocalPackages.plist
  apps_bundle_identifier = []
  success_apps.each do |app|
    apps_bundle_identifier << app.bundleIdentifier
  end
  
  if plist.update_localpackage_list("payload/installer/installer/LocalPackages.plist", apps_bundle_identifier)
    puts "[OK]"
  else
    puts "[FAILED]"
  end
  #PlistParser.add_source_into_localpackages_plist(xml_source, "payload/installer/installer/LocalPackages.plist", app_names)
    
  
  puts "You add #{apps.size} packages"
  puts "  Success : #{success_apps.size}  Packages"
  puts "  Failure : #{failure_apps.size}  Packages"

  failure_apps.each do |app|
    puts "    #{app.name}"
  end
  
  
end